<template>
  <div class="flow-statistics-page">
    <!-- 顶部导航 -->
    <van-nav-bar 
      title="流水统计" 
      left-arrow 
      @click-left="goBack"
    />
    
    <!-- 加载状态 -->
    <van-loading v-if="loading" class="page-loading">
      加载中...
    </van-loading>
    
    <!-- 我的流水统计 -->
    <div v-if="!loading && myStatistics" class="my-statistics-section">
      <div class="section-title">我的流水统计</div>
      
      <div class="statistics-cards">
        <!-- 总刷出 -->
        <div class="stat-card paid-out">
          <div class="card-icon">📤</div>
          <div class="card-content">
            <div class="card-label">总刷出</div>
            <div class="card-value">¥{{ formatAmount(myStatistics.totalPaidOut) }}</div>
            <div class="card-count">{{ myStatistics.transactionCountOut }}笔</div>
          </div>
        </div>
        
        <!-- 总刷入 -->
        <div class="stat-card paid-in">
          <div class="card-icon">📥</div>
          <div class="card-content">
            <div class="card-label">总刷入</div>
            <div class="card-value">¥{{ formatAmount(myStatistics.totalPaidIn) }}</div>
            <div class="card-count">{{ myStatistics.transactionCountIn }}笔</div>
          </div>
        </div>
        
        <!-- 流水余额 -->
        <div class="stat-card balance" :class="getBalanceClass(myStatistics.balance)">
          <div class="card-icon">{{ getBalanceIcon(myStatistics.balance) }}</div>
          <div class="card-content">
            <div class="card-label">流水余额</div>
            <div class="card-value">¥{{ formatAmount(myStatistics.balance) }}</div>
            <div class="card-status">{{ getBalanceStatus(myStatistics.balance) }}</div>
          </div>
        </div>
      </div>
      
      <!-- 平衡状态 -->
      <div class="balance-status" :class="getBalanceClass(myStatistics.balance)">
        <van-icon :name="getBalanceIcon(myStatistics.balance)" />
        <span>{{ getBalanceMessage(myStatistics.balance) }}</span>
      </div>
    </div>
    
    <!-- 流水排行榜 -->
    <div class="ranking-section">
      <div class="section-title">流水排行榜</div>
      
      <van-list
        v-model:loading="rankingLoading"
        :finished="rankingFinished"
        finished-text="没有更多了"
        @load="loadRanking"
      >
        <div 
          v-for="(item, index) in rankingList" 
          :key="item.userId"
          class="ranking-item"
        >
          <div class="rank-number" :class="getRankClass(index + 1)">
            {{ index + 1 }}
          </div>
          <div class="user-info">
            <div class="user-name">{{ item.userNickname || '用户' + item.userId }}</div>
            <div class="user-balance">余额: ¥{{ formatAmount(item.balance) }}</div>
          </div>
          <div class="flow-info">
            <div class="flow-out">刷出: ¥{{ formatAmount(item.totalPaidOut) }}</div>
            <div class="flow-in">刷入: ¥{{ formatAmount(item.totalPaidIn) }}</div>
          </div>
        </div>
      </van-list>
    </div>
    
    <!-- 平台统计 -->
    <div class="platform-section">
      <div class="section-title">平台统计</div>
      
      <div class="platform-cards">
        <div class="platform-card">
          <div class="card-label">总刷出</div>
          <div class="card-value">¥{{ formatAmount(platformStats.totalPaidOut) }}</div>
        </div>
        <div class="platform-card">
          <div class="card-label">总刷入</div>
          <div class="card-value">¥{{ formatAmount(platformStats.totalPaidIn) }}</div>
        </div>
        <div class="platform-card">
          <div class="card-label">平台余额</div>
          <div class="card-value">¥{{ formatAmount(platformStats.totalBalance) }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { 
  getMyFlowStatistics,
  getFlowRanking,
  getPlatformFlowStatistics
} from '@/api/user-flow-statistics'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const myStatistics = ref(null)
const rankingList = ref([])
const rankingLoading = ref(false)
const rankingFinished = ref(false)
const platformStats = ref({
  totalPaidOut: 0,
  totalPaidIn: 0,
  totalBalance: 0
})

// 加载我的流水统计
const loadMyStatistics = async () => {
  try {
    const result = await getMyFlowStatistics()
    myStatistics.value = result
  } catch (e) {
    console.error('加载我的流水统计失败:', e)
    showToast('加载失败')
  }
}

// 加载排行榜
const loadRanking = async () => {
  if (rankingLoading.value) return
  
  try {
    rankingLoading.value = true
    const result = await getFlowRanking()
    
    if (result.success && result.data) {
      rankingList.value = result.data
      rankingFinished.value = true
    }
  } catch (e) {
    console.error('加载排行榜失败:', e)
    showToast('加载失败')
  } finally {
    rankingLoading.value = false
  }
}

// 加载平台统计
const loadPlatformStats = async () => {
  try {
    const result = await getPlatformFlowStatistics()
    if (result.success && result.data) {
      platformStats.value = result.data
    }
  } catch (e) {
    console.error('加载平台统计失败:', e)
  }
}

// 格式化金额（分转元）
const formatAmount = (amountInCents) => {
  if (!amountInCents) return '0.00'
  return (amountInCents / 100).toFixed(2)
}

// 获取余额状态类名
const getBalanceClass = (balance) => {
  if (balance > 0) return 'positive'
  if (balance < 0) return 'negative'
  return 'balanced'
}

// 获取余额图标
const getBalanceIcon = (balance) => {
  if (balance > 0) return 'arrow-up'
  if (balance < 0) return 'arrow-down'
  return 'balance'
}

// 获取余额状态文本
const getBalanceStatus = (balance) => {
  if (balance > 0) return '盈余'
  if (balance < 0) return '不足'
  return '平衡'
}

// 获取余额消息
const getBalanceMessage = (balance) => {
  if (balance > 0) return '您的流水处于盈余状态，建议多参与刷出'
  if (balance < 0) return '您的流水不足，建议等待更多刷入'
  return '您的流水处于平衡状态'
}

// 获取排名类名
const getRankClass = (rank) => {
  if (rank === 1) return 'first'
  if (rank === 2) return 'second'
  if (rank === 3) return 'third'
  return 'normal'
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 组件挂载时加载数据
onMounted(async () => {
  try {
    await Promise.all([
      loadMyStatistics(),
      loadRanking(),
      loadPlatformStats()
    ])
  } finally {
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
.flow-statistics-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20px;
}

.page-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 20px 15px 15px;
}

.my-statistics-section {
  .statistics-cards {
    display: flex;
    flex-direction: column;
    gap: 15px;
    margin: 0 15px;
    
    .stat-card {
      background: #fff;
      border-radius: 12px;
      padding: 20px;
      display: flex;
      align-items: center;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      
      .card-icon {
        font-size: 32px;
        margin-right: 15px;
      }
      
      .card-content {
        flex: 1;
        
        .card-label {
          font-size: 14px;
          color: #666;
          margin-bottom: 5px;
        }
        
        .card-value {
          font-size: 24px;
          font-weight: bold;
          margin-bottom: 5px;
        }
        
        .card-count, .card-status {
          font-size: 12px;
          color: #999;
        }
      }
      
      &.paid-out {
        .card-value {
          color: #ff4d4f;
        }
      }
      
      &.paid-in {
        .card-value {
          color: #52c41a;
        }
      }
      
      &.balance {
        &.positive .card-value {
          color: #52c41a;
        }
        
        &.negative .card-value {
          color: #ff4d4f;
        }
        
        &.balanced .card-value {
          color: #1890ff;
        }
      }
    }
  }
  
  .balance-status {
    margin: 15px;
    padding: 15px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    
    &.positive {
      background: #f6ffed;
      color: #52c41a;
      border: 1px solid #b7eb8f;
    }
    
    &.negative {
      background: #fff2f0;
      color: #ff4d4f;
      border: 1px solid #ffccc7;
    }
    
    &.balanced {
      background: #f0f9ff;
      color: #1890ff;
      border: 1px solid #bae6fd;
    }
  }
}

.ranking-section {
  .ranking-item {
    background: #fff;
    margin: 0 15px 10px;
    padding: 15px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .rank-number {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
      margin-right: 15px;
      
      &.first {
        background: #ffd700;
        color: #fff;
      }
      
      &.second {
        background: #c0c0c0;
        color: #fff;
      }
      
      &.third {
        background: #cd7f32;
        color: #fff;
      }
      
      &.normal {
        background: #f0f0f0;
        color: #666;
      }
    }
    
    .user-info {
      flex: 1;
      
      .user-name {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin-bottom: 5px;
      }
      
      .user-balance {
        font-size: 14px;
        color: #666;
      }
    }
    
    .flow-info {
      text-align: right;
      
      .flow-out, .flow-in {
        font-size: 12px;
        color: #999;
        margin-bottom: 2px;
      }
    }
  }
}

.platform-section {
  .platform-cards {
    display: flex;
    gap: 10px;
    margin: 0 15px;
    
    .platform-card {
      flex: 1;
      background: #fff;
      padding: 15px;
      border-radius: 8px;
      text-align: center;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      
      .card-label {
        font-size: 12px;
        color: #666;
        margin-bottom: 8px;
      }
      
      .card-value {
        font-size: 16px;
        font-weight: bold;
        color: #333;
      }
    }
  }
}
</style>
